package com.xunshangwang.pinhaohuo.widgets;

import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.BackgroundColorSpan;
import android.util.AttributeSet;
import android.widget.TextView;

import com.xunshangwang.pinhaohuo.R;

import java.text.DecimalFormat;

/**
 * Created by xzp on 16/3/2.
 */
public class TimeTextView extends TextView{
    private long mLastTime;
    private DecimalFormat mDecimalFormat;
    private int mTimeBackgroundColor;
    public TimeTextView(Context context) {
        super(context);
        init(context);
    }

    public TimeTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public TimeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }
    private void init(Context context){
        mDecimalFormat=new DecimalFormat("00");
        updateLastTime(0,0);
        mTimeBackgroundColor= ContextCompat.getColor(context, R.color.time_num_background_color);
    }
    public void updateLastTime(long currentTime,long expireTime){
        removeCallbacks(mCountdownRunnable);
        mLastTime=expireTime-currentTime;
        if(mLastTime<0)
            mLastTime=0;
        post(mCountdownRunnable);
    }
    private Runnable mCountdownRunnable=new Runnable() {
        @Override
        public void run() {
            String hour=" "+mDecimalFormat.format(mLastTime / 3600)+" ";
            String minute=" "+mDecimalFormat.format(mLastTime/60%60)+" ";
            String second=" "+mDecimalFormat.format(mLastTime % 60)+" ";
            SpannableStringBuilder builder=new SpannableStringBuilder("剩余 ");
            SpannableString hourSpan=SpannableString.valueOf(hour);
            hourSpan.setSpan(new BackgroundColorSpan(mTimeBackgroundColor), 0, hour.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            builder.append(hourSpan);
            builder.append(":");
            SpannableString minuteSpan=SpannableString.valueOf(minute);
            minuteSpan.setSpan(new BackgroundColorSpan(mTimeBackgroundColor), 0, minute.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            builder.append(minuteSpan);
            builder.append(":");
            SpannableString secondSpan=SpannableString.valueOf(second);
            secondSpan.setSpan(new BackgroundColorSpan(mTimeBackgroundColor),0,second.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            builder.append(secondSpan);
            builder.append(" 结束");
            setText(builder);
            if(mLastTime>0){
                postDelayed(mCountdownRunnable,1000);
            }
            mLastTime--;
        }
    };
}
